<?php
namespace app\controller;

use app\BaseController;
use app\model\ArticleModel;
use think\facade\View;

/**
 * 资讯列表
 */
class News extends BaseController
{
    public function index()
    {
        $where = [
            'deleted' => 0,
            'status_flag' => 0,
        ];
        $list = ArticleModel::where($where)->order( "show_time desc")->paginate(10);

        // 把分页数据赋值给模板变量list
        View::assign('list', $list);

        // 获取分页显示
        $page = $list->render();
        // 分页数据
        View::assign('page', $page);


        // 热门
        $hot = ArticleModel::where($where)->order('hits', 'desc')->limit(5)->select();
        View::assign('hot', $hot);

        if ($this->isMobile())
        {
            return View::fetch('wap_index');
        } else {
            return View::fetch();
        }
    }


    /**
     * 资讯详情
     */
    public function detail($id = 1)
    {


        // 获取资讯详情
        $article = ArticleModel::find($id);
        View::assign('data', $article);

        // 流量量 hits 自增1
        ArticleModel::where('id', $id)->inc('hits')->update();

        // 上一篇
        $prev = ArticleModel::where('id', '<', $id)->order('show_time', 'desc')->find();
        View::assign('prev', $prev);

        // 下一篇
        $next = ArticleModel::where('id', '>', $id)->order('show_time', 'asc')->find();
        View::assign('next', $next);

        // 热门
        $where = [
            'deleted' => 0,
            'status_flag' => 0,
        ];
        $hot = ArticleModel::where($where)->order('hits', 'desc')->limit(5)->select();
        View::assign('hot', $hot);



        if ($this->isMobile())
        {
            return View::fetch('wap_detail');
        } else {
            return View::fetch();
        }
    }

    /**
     * 异步ajax加载资讯列表
     */
    public function ajaxList()
    {
        $page = input('get.page', 1, 'intval'); // 获取页码
        $limit = 10;

        $where = [
            'deleted' => 0,
            'status_flag' => 0,
        ];

        // 分页获取数据
        $list = ArticleModel::where($where)
            ->order("show_time desc")
            ->page($page, $limit)
            ->select();

        if ($list->isEmpty()) {
            return json(['code' => 0, 'msg' => '暂无更多数据']);
        }

        // 格式化数据（可选）
        $data = [];
        foreach ($list as $item) {
            $data[] = [
                'id' => $item['id'],
                'title' => $item['title'],
                'show_time' => date('Y-m-d', strtotime($item['show_time'])),
                'thumb' => $item['thumb'],
            ];
        }

        return json([
            'code' => 1,
            'msg' => '加载成功',
            'data' => $data
        ]);
    }



}
